<template>
  <div class="role_edit">
    <div>
      <Row :gutter="20" class="code-row-bg">
        <Col span="24" style="border:none;">
          <div style="min-height: 380px;">
            <el-tree
              :data="baseData"
              :show-checkbox="true"
              ref="roleMenusTree"
              :props="treeProps"
              node-key="id"
              icon-class="ivu-icon-ios-arrow-forward"
              :check-strictly="true"
              @check="check"
            >
              <!-- :load="loadNode" lazy> -->
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                  <Icon type="lightbulb" v-if="data.menuType == '2'" />
                  <Icon type="navicon-round" v-if="data.menuType == '1'" />
                  <Icon type="ios-ionic-outline" v-if="data.menuType == '0'" />
                  <Icon type="android-home" v-if="data.resourceType == '1'"></Icon>
                  <Icon type="android-cloud-outline" v-if="data.resourceType == '2'"></Icon>
                  <Icon type="android-cloud" v-if="data.isPublicAPI"></Icon>
                  {{ node.label }}
                </span>
              </span>
            </el-tree>
          </div>
        </Col>
      </Row>
    </div>
    <Spin size="large" fix v-if="isQuery"></Spin>
  </div>
</template>
<script>
import { queryMenusResourceTree, saveAssignedResource } from "@/api/roleApi.js";
import locales from "./locales.js";

export default {
  name: "permissionedit",
  mixins: [locales],
  props: {
    roleId: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    return {
      baseData: [],
      checkedList: [],
      treeProps: {
        label: "title",
        children: "children"
      },
      isQuery: false,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {},
  created: function() {
    this.init();
    this.$emit("SetTitle", this.$t("module.role.permissionMaList"));
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    init() {
      this.isQuery = true;
      let param = {
        roleId: this.roleId
      };
      queryMenusResourceTree(param).then(treeData => {
        this.isQuery = false;
        const baseData = this.initChildren(treeData.data) || [];
        // console.log();
        this.baseData = this.filterBaseData(baseData);
        // 设置选中节点
        this.$refs["roleMenusTree"].setCheckedKeys(this.checkedList);
      });
    },
    filterBaseData(datas) {
      const source = datas.reduce((obj, item) => {
        Array.isArray(obj[item.productCode]) || (obj[item.productCode] = []);
        obj[item.productCode].push(item);
        return obj;
      }, {});
      const newDatabase = [];
      for (const [key, val] of Object.entries(source)) {
        const productItem =
          key == "" ? { vsiKey: "public", vsiValue: "公共功能" } : {vsiKey: key, vsiValue: key};
        newDatabase.push({
          id: productItem.vsiKey,
          title: productItem.vsiValue,
          children: val,
          first: true
        });
      }
      return newDatabase;
    },
    initChildren(children) {
      children.forEach(node => {
        if (node.menuType == "1") {
          // 当前节点是菜单目录
          node.children = this.initChildren(node.menuChildren);
          node.title = node.menuName;
        } else if (node.menuType == "0") {
          // 当前节点是菜单
          node.children = this.initChildren(node.resourceChildren);
          node.title = node.menuName;
        } else if (node.resourceType) {
          // 当前节点是资源
          node.children = this.initChildren(node.resourceChildren);
          node.title = node.resourceName;
        } else {
          // 当前节点是未知类型
          node.children = this.initChildren(node.menuChildren);
          node.title = node.menuName;
        }
        // 勾选的节点
        if (node.selected == 1) {
          this.checkedList.push(node.id);
        }
      });

      return children;
    },
    //保存角色权限信息
    save() {
      this.actions[0].loading = true;
      let checkedList = this.$refs["roleMenusTree"].getCheckedNodes();
      let menuIds = [];
      let resourceIds = [];
      for (let item of checkedList) {
        if (!!item.menuType) {
          menuIds.push(item.id);
        } else if (!!item.resourceType) {
          resourceIds.push(item.id);
        }
      }
      let params = {
        menuId: menuIds,
        resourceId: resourceIds,
        roleId: this.roleId
      };
      saveAssignedResource(params)
        .then(data => {
          this.actions[0].loading = false;
          this.$message.success({
            content: this.$t("module.role.assignSucccess"),
            duration: 3
          });
          this.$emit("Close");
        })
        .catch(err => {
          this.actions[0].loading = false;
        });
    },
    check(data, status) {
      if (data.first) {
        this.$refs["roleMenusTree"].setChecked(data.id, false);
        return;
      }
      let currentNode = this.$refs["roleMenusTree"].getNode(data.id);
      let checked = currentNode.checked;
      if (checked) {
        // 已勾选时
        // 勾选子
        this.checkChildren(data);
        // 勾选父
        this.checkParent(data);
      } else {
        // 未勾选时
        // 取消勾选子
        this.checkChildren(data, checked);
        // 如果是最后一个取消勾选的子，则取消勾选父
        this.checkParent(data, checked);
      }
    },
    // 勾选子
    checkChildren(currentNode, checked = true) {
      let children = null;
      if (currentNode.resourceChildren && currentNode.resourceChildren.length > 0) {
        children = currentNode.resourceChildren;
      } else if (currentNode.menuChildren && currentNode.menuChildren.length > 0) {
        children = currentNode.menuChildren;
      }
      if (children) {
        children.forEach(node => {
          // 设置选中节点
          this.$refs["roleMenusTree"].setChecked(node.id, checked, true);
          // 勾选子
          this.checkChildren(node, checked);
        });
      }
    },
    // 勾选父
    checkParent(currentNode, checked = true) {
      let parentNode = null;
      if (currentNode.parentResourceId) {
        // 父是资源
        parentNode = this.$refs["roleMenusTree"].getNode(currentNode.parentResourceId);
      } else if (currentNode.menuModuleId) {
        // 父是菜单目录
        parentNode = this.$refs["roleMenusTree"].getNode(currentNode.menuModuleId);
      } else if (currentNode.menuId) {
        // 父是菜单
        parentNode = this.$refs["roleMenusTree"].getNode(currentNode.menuId);
      }
      if (parentNode) {
        // 如果是最后一个取消勾选的子，则取消勾选父
        if (!checked && this.hasOtherCheckedChild(parentNode.data)) {
          return;
        }
        // 设置选中节点
        this.$refs["roleMenusTree"].setChecked(parentNode.key, checked, true);
        // 勾选父
        this.checkParent(parentNode.data, checked);
      }
    },
    hasOtherCheckedChild(parent) {
      let children = null;
      if (parent.resourceChildren && parent.resourceChildren.length > 0) {
        children = parent.resourceChildren;
      } else if (parent.menuChildren && parent.menuChildren.length > 0) {
        children = parent.menuChildren;
      }
      if (children) {
        let checkedChild = children.find(child => {
          let childNode = this.$refs["roleMenusTree"].getNode(child.id);
          if (childNode.checked) {
            return true;
          }
        });
        if (checkedChild) {
          return true;
        } else {
          return false;
        }
      }
      return true;
    }
  },
  watch: {},
  directives: {}
};
</script>

<style>
.role_edit .el-tree > div > div > label {
  display: none;
}
</style>